package com.ihd.ihardwarefactorytools.view.view;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.ihd.ihardwarefactorytools.databinding.ActivityMainBinding;
import com.ihd.ihardwarefactorytools.R;
import com.ihd.ihardwarefactorytools.common.utils.DataUtils;
import com.ihd.ihardwarefactorytools.pojo.ListRes;
import com.ihd.ihardwarefactorytools.pojo.OPValue;
import com.ihd.ihardwarefactorytools.view.viewmodel.MainViewModel;
import com.ihd.ihardwarefactorytools.view.viewmodel.RecyclerViewSpacesItemDecoration;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.OptionPicker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.wowjoy.commonlibrary.LiveDataBus.LiveDataBus;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.utils.BLEUtils;
import cn.wowjoy.commonlibrary.utils.DensityUtil;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.HexUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;
import cn.wowjoy.commonlibrary.widget.MPopupwindow;
import cn.wowjoy.commonlibrary.widget.titlebar.TitleBar;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {
    private int REQUEST_CODE_BLUETOOTH_ON = 100;
    private MPopupwindow mWhoPop;
    private List<ListRes> datas;
    private OptionPicker mSexPicker;
    private List<OPValue> sexs = new ArrayList<>();
    private String dValue;
    private long total = 0;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(false).init();

        binding.mtitlebar.setTitle("享睿专用测试工具");
        binding.mtitlebar.setTitleColor(getResources().getColor(R.color.C_FFFFFF));
        binding.mtitlebar.addAction(new TitleBar.Action() {
            @Override
            public String getText() {
                return null;
            }

            @Override
            public int getDrawable() {
                return R.drawable.nbicon_more;
            }

            @Override
            public void performAction(View view) {
                mWhoPop.show(view);
            }
        });

        mWhoPop = new MPopupwindow(this, viewModel.mWhoAdapter, DensityUtil.getWidthPixels() / 4, DensityUtil.dip2px(45));
        viewModel.setActions();

        LiveDataBus.get().with("1", Integer.class).observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer type) {
                mWhoPop.dismiss();
                total += Integer.parseInt(binding.singleNum.getText().toString());
                binding.total.setText(String.valueOf(total));
                SPUtils.putLong("TOTAL", total);
                for (int i = 0; i < datas.size(); i++) {
                    datas.get(i).setOmu("");
                }
                viewModel.mConcernedAdapter.notifyDataSetChanged();
                binding.singleNum.setText("0");
            }
        });

        binding.mjRV.setAdapter(viewModel.mConcernedAdapter);
        for (int i = 0; i >= -80; i--) {
            sexs.add(new OPValue(String.valueOf(i)));
        }
        mSexPicker = new OptionPicker.Builder(this, 1, new OptionPicker.OnOptionSelectListener() {
            @Override
            public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
                binding.distance.setText(sexs.get(selectedPosition[0]).getValue());
                dValue = sexs.get(selectedPosition[0]).getValue();
                SPUtils.putString("DVALUE", dValue);
            }
        }).create();

        dValue = SPUtils.getString("DVALUE", "-80");
        binding.distance.setText(dValue);
        mSexPicker.setDataWithValues(sexs, dValue);
        binding.distance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSexPicker.show();
            }
        });
        total = SPUtils.getLong("TOTAL", 0);
        binding.total.setText(String.valueOf(total));
        datas = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            datas.add(new ListRes(String.valueOf(i + 1), String.valueOf(10 + i * 2), ""));
        }
        viewModel.setList(datas);

        if (!BLEUtils.getInstance().isBluetoothOpened()) {
            Intent requestBluetoothOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(requestBluetoothOn, REQUEST_CODE_BLUETOOTH_ON);
        } else
            connectBluetooth();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected Class getViewModelClass() {
        return MainViewModel.class;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    connectBluetooth();
                    break;
                case Activity.RESULT_CANCELED:
                    ToastUtils.showLong(this, "请手动打开蓝牙再进入app，才能获取数据哦~");
                    break;
                default:
                    break;
            }
        }
    }

    private void connectBluetooth() {
        BLEUtils.getInstance().search(new SearchRequest.Builder().searchBluetoothLeDevice(86400000).build(), new SearchResponse() {
            @Override
            public void onSearchStarted() {
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (Integer.parseInt(dValue) <= device.rssi) {
                    Beacon beacon = new Beacon(device.scanRecord);
                    if (DataUtils.isValidDevice(beacon.mBytes) && DataUtils.isStable(beacon.mBytes)) {
                        setData(DataUtils.getWeight(beacon.mBytes), DataUtils.getOmu(beacon.mBytes));
                    }
                }
            }

            @Override
            public void onSearchStopped() {
            }

            @Override
            public void onSearchCanceled() {
            }
        });
    }

    private synchronized void setData(String weight, String omu) {
        int size = 0;
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).getWeight().equals(weight)) {
                datas.get(i).setOmu(omu);
            }
            if (!TextUtils.isEmpty(datas.get(i).getOmu()))
                size++;
        }
        binding.singleNum.setText(String.valueOf(size));
        viewModel.mConcernedAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        SPUtils.putLong("TOTAL", total);
        BLEUtils.getInstance().stopSearch();
        super.onDestroy();
    }
}
